package cc.catface.api.biz;

import cc.catface.common.aspect.NetLog;
import cc.catface.common.fastdfs.UploadMediaUtil;
import cc.catface.common.output.Result;
import cc.catface.dao.biz.fds.UploadOUTDTO;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("fastdfs")
@Api(tags = "fastdfs文件服务器")
public class FastdfsController {
    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Value("${fdfs.host}")
    private String host;

    @SneakyThrows
    @ApiOperationSupport(order = 10)
    @NetLog(value = "图片或视频文件上传", skip = true)
    @ApiOperation(value = "图片或视频文件上传=开发完成")
    @ApiResponses(@ApiResponse(code = 200, message = "Success", response = UploadOUTDTO.class))
    @PostMapping("upload")
    public Result<List<UploadOUTDTO>> upload(@RequestParam MultipartFile[] files) {
        List<UploadOUTDTO> outs = new ArrayList<>();
        for (MultipartFile f : files) {
            String group = UploadMediaUtil.upload(f, fastFileStorageClient);
            UploadOUTDTO out = new UploadOUTDTO();
            out.setFilename(f.getOriginalFilename());
            out.setUrl(host + group);
            outs.add(out);
        }
        return Result.success(outs);
    }

    @SneakyThrows
    @Deprecated
    @ApiOperationSupport(order = 20)
    @NetLog("图片或视频文件下载")
    @ApiOperation(value = "图片或视频文件下载=已废弃")
    @ApiResponses(@ApiResponse(code = 200, message = "Success"))
    @PostMapping("download")
    public byte[] download(String fileId) {
        int index = fileId.indexOf("/");
        String s1 = fileId.substring(0, index);
        String s2 = fileId.substring(index + 1);
        return fastFileStorageClient.downloadFile(s1, s2, new DownloadByteArray());
    }

    //将download接口下载的文件byte[]写到本地
    @SneakyThrows
    private void writeBytes2Local(byte[] bytes) {
        OutputStream out = new FileOutputStream("D:\\adding\\" + System.currentTimeMillis() + ".jpg");
        InputStream is = new ByteArrayInputStream(bytes);
        byte[] buff = new byte[1024];
        int len = 0;
        while ((len = is.read(buff)) != -1) {
            out.write(buff, 0, len);
        }
        is.close();
    }
}
